package com.haoyun.mirage.gateway.service.impl;

import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.haoyun.mirage.gateway.client.UserServiceClient;
import com.haoyun.mirage.gateway.dto.MenuDTO;
import com.haoyun.mirage.gateway.service.PermissionService;
import com.xiaoleilu.hutool.collection.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author lengleng
 * @date 2017/10/28
 */
@Slf4j
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private UserServiceClient userServiceClient;
    @Autowired
    private PathMatcher pathMatcher;

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        //解决跨域问题
        if (StrUtil.equals(HttpMethod.OPTIONS.name(),request.getMethod())){
            return true;
        }
        Object principal = authentication.getPrincipal();
        List<SimpleGrantedAuthority> grantedAuthorityList = (List<SimpleGrantedAuthority>) authentication.getAuthorities();
        boolean hasPermission = false;
        if (principal != null) {
            if (CollectionUtil.isEmpty(grantedAuthorityList)) {
                log.warn("角色列表为空：{}", authentication.getPrincipal());
                return hasPermission;
            }

            Set<MenuDTO> urls = new HashSet<>();
            for (SimpleGrantedAuthority authority : grantedAuthorityList) {
                if (!StrUtil.equals(authority.getAuthority(), "ROLE_USER")) {
                    List<MenuDTO> menuDTOS = userServiceClient.findMenuByRole(authority.getAuthority());
                    urls.addAll(menuDTOS);
                }
            }
            for (MenuDTO url : urls) {
                log.info("This is gateway findMenuByRole : method {},url {} ", url.getMethod(), url.getUrl());
            }

            for (MenuDTO menu : urls) {
                if (StringUtils.isNotEmpty(menu.getUrl()) && pathMatcher.match(menu.getUrl(), request.getRequestURI())
                        && request.getMethod().equalsIgnoreCase(menu.getMethod())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        log.info(" This hasPermission ==== {}", hasPermission);
        return hasPermission;
    }
}
